<template>
  <div v-loading="pageLoading" class="el-table-content">
    <div v-if="!route.query.isShowXml" class="top-box margin-bottom-xs margin-left-lg">
      <el-tabs v-model="nowActiveName" @tab-click="tabClick">
        <el-tab-pane label="审核信息" name="first">
          <dynamic-form ref="dynamicForm" :size="size" :form-config="formConfig" />
          <div>
            <el-collapse v-model="auditActiveNames">
              <el-collapse-item name="1">
                <template #title>
                  <div class="wk-editform-header flex justify-between align-center width-full">
                    <span class="edit-header-title">附件</span>
                  </div>
                </template>

                <!-- 表格 -->
                <div class="table el-table-content">
                  <el-table :data="attachmentTableData" border>
                    <el-table-column type="index" label="序号" width="80" />
                    <el-table-column show-overflow-tooltip property="fileType" label="单据类型" />
                    <el-table-column show-overflow-tooltip property="fileName" label="文件名称">
                      <template #default="scope">
                        <span class="blue pointer" @click="handleDownload(scope.row)">{{ scope.row.fileName }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column show-overflow-tooltip property="handleTime" label="操作">
                      <template #default="scope">
                        <el-button type="text" class="blue" @click="handleDownload(scope.row)">
                          下载
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
          <div class="bg-white padding-xs text-center">
            <el-button @click="handleBack">
              返回
            </el-button>
            <el-button v-if="showreject" type="primary" @click="handleReject">
              驳回
            </el-button>
            <el-button v-if="showApply" type="primary" :loading="submitLoading" @click="handleApply">
              通过
            </el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="全程记录信息" name="second">
          <el-collapse v-model="activeNames">
            <el-collapse-item name="1">
              <template #title>
                <div class="wk-editform-header flex justify-between align-center width-full">
                  <span class="edit-header-title">流程进度</span>
                </div>
              </template>
              <div>
                <xml-viewer ref="xmlViewerRef" :completed-nodes="completedNodes" :reject-nodes="rejectNodes" />
              </div>
            </el-collapse-item>
            <el-collapse-item name="2">
              <template #title>
                <div class="wk-editform-header flex justify-between align-center width-full">
                  <span class="edit-header-title">审批记录</span>
                </div>
              </template>

              <!-- 表格 -->
              <div class="table el-table-content">
                <el-table :data="tableData" border stripe highlight-current-row style="width: 100%">
                  <el-table-column type="index" label="序号" width="80" />
                  <el-table-column show-overflow-tooltip property="nodeName" label="节点名称" />
                  <el-table-column show-overflow-tooltip property="approveUserName" label="电子签名" />
                  <el-table-column show-overflow-tooltip property="handleTime" label="签名日期" />
                  <el-table-column show-overflow-tooltip property="" label="操作" />
                  <el-table-column show-overflow-tooltip property="completeComment" label="留言" />
                  <el-table-column show-overflow-tooltip property="nodeStatus" label="流程当前审批状态">
                    <template #default="scope">
                      {{ scope.row.nodeStatus ? xmlStatusObj[scope.row.nodeStatus] : '-' }}
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div v-else>
      <div class="padding-xs">
        <!-- 已办任务 流程图查看 -->
        <div>
          <div class="wk-editform-header font-size-lg">
            <span class="margin-left-xs">{{ route.query.taskName || '' }}</span>
            <span class="margin-left-lg">业务编号{{ route.query.businessKey }}</span>
          </div>
        </div>
        <xml-viewer ref="xmlViewerRef" :completed-nodes="completedNodes" :reject-nodes="rejectNodes" />
      </div>
    </div>
    <el-dialog v-dialogDrag :close-on-click-modal="false" width="40%" title="驳回提示" v-model="dialogVisible" append-to-body>
      <div class="wk-editform-header margin-bottom-xs">
        <div class="margin-bottom-xs">
          <span class="red-star">*</span>
          请输入驳回原因：
        </div>
        <el-input
          v-model="rejectForm.preExamReason"
          :rows="3"
          placeholder="请输入驳回原因，最多200字"
          type="textarea"
          maxlength="200"
          show-word-limit
        />
      </div>

      <div slot="footer">
        <el-button @click="closeDialog">
          取 消
        </el-button>
        <el-button type="primary" :loading="rejectLoading" @click="submitReject">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useTable } from '@wlydfe/pro-ui'
import { workTableApi } from '@/api';
import DynamicForm from '@/views/workTable/components/dynamic.vue'
import xmlViewer from '@/views/workTable/components/xml.vue'
import { downloadFile } from '@/utils/exportUtil'
import { hasAuth } from '@/router/utils'

const props = defineProps({
  type: {
    type: String,
    default: ''
  }
})

const route = useRoute()
const router = useRouter()

// 附件表格
const attachmentTableData = ref([])
const auditActiveNames = ref(['1'])
const activeNames = ref(['1', '2']) // 默认展开第一个折叠面板
const completedNodes = ref([]) // 已完成节点 ID 列表
const rejectNodes = ref([]) // 拒绝节点 ID 列表
const xmlStatusObj = {
    '10': '审批中',
    '20': '已结束'
};
const tableData = ref([])
const nowActiveName = ref('first')
const pageLoading = ref(false)
const evaluationTarget = ref({})
const limitStatusStatusObj = ref({})
const detail = ref({})
const formConfig = ref({})
const tabsModel = ref('0')
const rejectLoading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const rejectForm = ref({
  preExamReason: ''
})
const downloadLoading = ref(false)
const dynamicForm = ref(null)
const xmlViewerRef = ref(null)

// PlusPage 配置
const { buttons: attachmentButtons } = useTable()
attachmentButtons.value = [
  {
    text: '下载',
    code: 'download',
    props: { type: 'primary', link: true },
    onClick: (params) => {
      if (params?.row) {
        handleDownload(params.row)
      }
    },
  },
]

const showApply = computed(() => {
  return route.query.isEdit === 'true' && hasAuth('submitBtn');
})

const showreject = computed(() => {
  return route.query.isEdit === 'true' && hasAuth('rejectBtn');
})

const formRef = computed(() => {
  return dynamicForm.value
})

onMounted(() => {
  pageLoading.value = true
  // 如果route.query.isShowXml为true，则不获取 getTaskForm()，否则需要获取 getTaskForm()。promise.all()方法可以并行执行多个异步操作
  Promise.all([
    getTaskRecord(),
    getXmlView(),
    ...(!route.query.isShowXml ? [getTaskForm()] : [])
  ]).then(() => {
    // 这里可以处理加载完成后的逻辑
    pageLoading.value = false
  }).catch(() => {
    pageLoading.value = false
  })
})

function handleDownload(row) {
  if (downloadLoading.value) return
  downloadLoading.value = true
  // 从行数据中获取文件路径，这里需要根据实际数据结构调整
  const filePath = row.filePath || row.fileUrl || ''
  if (!filePath) {
    ElMessage.warning('文件路径不存在')
    return
  }

  // 显示加载状态
  ElMessage.info('正在下载文件...')

  workTableApi.downloadAttachment(filePath).then((res) => {
    // console.log('下载响应:', res)

    // 检查响应状态
    if (res.status !== 200) {
      ElMessage.error('下载失败')
      return
    }

    // 对于 blob 响应，res 是整个 response 对象，需要取 res.data
    const blobData = res.data

    // 检查响应是否为空
    if (!blobData || blobData.size === 0) {
      ElMessage.error('文件内容为空')
      return
    }

    // 获取正确的 MIME 类型
    let mimeType = 'application/octet-stream'
    if (blobData.type && blobData.type !== 'application/octet-stream') {
      mimeType = blobData.type
    } else {
      // 根据文件扩展名推断 MIME 类型
      const extension = filePath.split('.').pop()?.toLowerCase()
      const mimeTypes = {
        'jpg': 'image/jpeg',
        'jpeg': 'image/jpeg',
        'png': 'image/png',
        'gif': 'image/gif',
        'pdf': 'application/pdf',
        'doc': 'application/msword',
        'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'xls': 'application/vnd.ms-excel',
        'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'txt': 'text/plain',
        'mp4': 'video/mp4',
        'mp3': 'audio/mpeg'
      }
      mimeType = mimeTypes[extension] || 'application/octet-stream'
    }

    // console.log('使用的 MIME 类型:', mimeType)

    // 创建 Blob 对象
    const blob = new Blob([blobData], { type: mimeType })

    // 使用行数据中的文件名，如果没有则从路径中提取
    const fileName = row.fileName || filePath.split('/').pop() || 'download'

    // console.log('下载文件名:', fileName)

    // 使用项目中的下载工具函数
    downLoadFile(blob, fileName, () => {
      ElMessage.success('文件下载成功')
    })
  }).finally(() => {
    downloadLoading.value = false
  })
}

// 加载详情
function loadDetail(id, number) {
  pageLoading.value = true
  const params = {
    processInstanceId: route.query.id,
    processNo: route.query.number
  }
  return new Promise((resolve, reject) => {
    workTableApi.queryDetail(params).then(async(data) => {
      if (data.model && data.model.length > 0) {
        detail.value = data.model[0] || {}
        getXmlView()
        getTaskRecord()
      }
      resolve()
    }).catch(() => {
      reject()
    })
  })
}

// 获取任务审批记录
function getTaskRecord() {
  const params = {
    processInstanceId: route.query.id
  }
  workTableApi.queryAuditTaskList(params).then((res) => {
    if (res.model && res.model.length > 0) {
      tableData.value = res.model[0]?.historyAuditNodes.map((i) => {
        return {
          ...i,
          approveUserName: i.approveUser.approveUserName || ''
        }
      }) || []
      completedNodes.value = tableData.value.map(item => item.activityId) // 更新已完成节点 ID 列表
    } else {
      tableData.value = []
      completedNodes.value = []
    }
  })
}

// 获取xml流程图
function getXmlView() {
  const params = {
    processInstanceId: route.query.id,
    highlight: 1
  }

  workTableApi.queryRunningFlowChart(params)
    .then(res => {
      if (res.succeed) {
        // 流程结束highLightXml为空，用chartXml代替
        xmlViewerRef.value.getHilightProcessInfo(res.model[0].highLightXml || res.model[0].chartXml)
      }
    })
    .finally(() => {
    })
}

// 这里的表单是动态表单
function getTaskForm() {
  return new Promise((resolve, reject) => {
    const params = {
      processInstanceId: route.query.id,
      taskId: route.query.taskId
    }
    workTableApi.queryTaskForm(params).then((res) => {
      if (res.model && res.model.length > 0) {
        const data = {
          formDefinition: JSON.parse(res.model[0].formDefinition),
          processVar: res.model[0].processVar || {}
        }
        attachmentTableData.value = res.model[0].processVar.fileInfo || []
        const processedData = processFormData(data)
        // 3. 提取表单组件配置
        const originData = processedData.formDefinition

        // 4. 延迟后批量应用数据到表单（模拟异步处理完成）
        nextTick(() => {
          formConfig.value = applyDataToForm(originData)
        })
      }
      resolve()
    }).catch(() => {
      reject()
    })
  })
}

// 1. 数据处理函数 - 只处理数据，不涉及表单操作
function processFormData(rawData) {
  const { formDefinition = '', processVar = {}} = rawData

  // 深拷贝组件定义，避免修改原始数据
  const components = JSON.parse(JSON.stringify(formDefinition.components))

  // 处理组件数据
  components.forEach(component => {
    const value = processVar[component.key]

    if (value) {
      // 根据组件类型处理值
      if (component.type === 'textfield' || component.type === 'textarea') {
        component.newValues = value
      } else if (component.type === 'number') {
        component.newValues = parsePrice(value)
      } else if (component.type === 'select') {
        // 找到匹配的选项
        const option = component.values?.find(opt => opt.value === value)
        component.newValues = option ? option.value : value
      }
      // 其他组件类型...
    }
  })
  if (route.query.isEdit === 'true') {
    // 如果是编辑状态，设置所有组件为可编辑,不赋值
    return {
      processVar,
      formDefinition
    }
  } else {
    // 查看，根据processVar，匹配出key对应的字段，赋值展示到页面中
    return {
      processVar,
      formDefinition: {
        ...formDefinition,
        components
      }
    }
  }
}

function applyDataToForm(configData) {
  if (!configData || !configData.components || !Array.isArray(configData.components)) {
    return { components: [] }
  }

  return {
    ...configData,
    components: configData.components.map(component => {
      // 创建一个新对象，包含原始组件的所有属性
      const newComponent = { ...component }

      // 添加与label同名的字段
      if (component.key) {
        // 处理values属性
        newComponent[component.key] = component.newValues
      }

      return newComponent
    })
  }
}

function tabClick(tab, event) {
  nextTick(() => {
  })
}

// 返回上一页
function handleBack() {
  router.back()
}

// 处理通过
function handleApply() {
  handleAction('10', '确定要审核通过吗？')
}

// 处理驳回
const handleReject = () => {
  if (rejectLoading.value) return // 防止重复提交
  Promise.all([
    dynamicForm.value.checkComponent()
  ]).then(() => {
    dialogVisible.value = true
  }).catch(() => {
    rejectLoading.value = false
  })
}

// 处理提交驳回-调用接口
function submitReject() {
  if (!rejectForm.value.preExamReason) {
    ElMessage.error('请输入驳回原因')
    return
  }
  handleAction('20', '', rejectForm.value.preExamReason)
}

// 统一处理审核操作
async function handleAction(status, confirmMsg, comment = '') {
  // 状态文本映射，用于提示信息
  const statusTextMap = {
    '10': '通过',
    '20': '驳回'
  }

  try {
    // 防止重复提交
    const loadingKey = status === '10' ? 'submitLoading' : 'rejectLoading'
    if (loadingKey === 'submitLoading' ? submitLoading.value : rejectLoading.value) return

    // 表单验证
    await Promise.all([
      dynamicForm.value.checkComponent()
    ])

    // 显示确认对话框
    if (confirmMsg) {
      await ElMessageBox.confirm(confirmMsg, '提交确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
    }

    // 显示加载状态
    if (loadingKey === 'submitLoading') {
      submitLoading.value = true
    } else {
      rejectLoading.value = true
    }

    // 准备数据
    const payload = getFormData(status)
    if (comment) payload.completeComment = comment

    // 提交请求
    const res = await workTableApi.submitTask(payload)

    // 处理结果
    if (res.succeed) {
      ElMessage.success(`${statusTextMap[status]}成功`)
      dialogVisible.value = false;
      setTimeout(() => router.back(), 300);
    } else {
      throw new Error(res.message || `${statusTextMap[status]}失败`)
    }
  } catch (error) {
    // 处理错误
    if (error.message && error.message !== 'cancel') {
      ElMessage.error(error.message)
    }
  } finally {
    // 重置加载状态
    submitLoading.value = false
    rejectLoading.value = false
  }
}

// 获取表单数据
function getFormData(status) {
  return {
    processNo: route.query.number,
    processInstanceId: route.query.id,
    completeResult: status, // [10-通过,20-未通过]
    customVar: dynamicForm.value.getComponnetValue()
    // TODO 上线取消掉
    // completeUserId: 'demo2',
    // completeUserName: 'demo2'
  }
}

function closeDialog() {
  rejectForm.value.preExamReason = ''
  dialogVisible.value = false
}

function parsePrice(value) {
  // 这里需要实现 parsePrice 函数，根据实际需求调整
  return value
}
</script>
<style lang="scss" scoped>
.baseinfo-view-page{
  .wk-editform-header{ line-height: normal;}
  .el-collapse-item__content{ padding-bottom: 0;}
  ::deep .el-descriptions-item__label {
    width: 110px; /* 设置标签宽度为 110px */
  }

}
.el-table-content{
  overflow: auto;
  background-color: #fff;
  width: 100%!important;
}
.font-size-lg{
  font-size: 16px;
}
.red-star{
  color: #F56C6C;
}

.edit-header-title {
  border-left: 4px solid #c41230;
  padding-left: 10px;
  font-size: 14px;
  line-height: 21px;
  height: 21px;
  color: #000;
  position: relative;
}

.padding-xs {
  padding: 10px;
}

.margin-bottom-xs {
  margin-bottom: 10px;
}
</style>
